package com.howie.hmvc.paramparse;

import java.lang.annotation.Annotation;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;

import com.howie.hmvc.annotations.DateFormat;
import com.howie.hmvc.annotations.Valid;
import com.howie.hmvc.exception.ArguErrorException;

public class ParamDates extends AbsParamParse{

	private String dateFormat = "yyyy-MM-dd";
	private boolean required;
	
	@Override
	public void init(Annotation[] an) throws Exception {
		Valid valid = getValid(an);
		if(valid != null){
			required = valid.required();
		}
		DateFormat format = getDateFormat(an);
		if(format != null){
			dateFormat = format.value();
		}
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String[] values = request.getParameterValues(name);
		if(values == null){
			if(required){
				throw new ArguErrorException(name,"required",null);
			}
		}else{
			Date[] vals = new Date[values.length];
			for(int i=0;i<values.length;i++){
				try {
					vals[i] = DateUtils.parseDate(values[i],new String[]{dateFormat});
				} catch (Exception e) {
					LOG.debug("参数["+name+"]解析出错");
				}
				if(vals[i] == null && required){
					throw new ArguErrorException(name,"required",null);
				}
			}
			return vals;
		}
		return null;
	}
	
	/*
	 * 获取DateFormat注解
	 * @param an
	 * @return
	 */
	protected DateFormat getDateFormat(Annotation[] ans){
		for(Annotation a : ans){
			if(a instanceof DateFormat){
				return (DateFormat)a;
			}
		}
		return null;
	}
	
}
